package session

import (
	"crypto/md5"
	"fmt"
	"io"
	"math/rand"
	"strconv"
	"sync"
	"time"
)

var (
	once sync.Once
)

func GetAppId(t int, port int) uint64 {
	nano := time.Now().UnixNano()
	once.Do(func() {
		rand.Seed(nano)
	})

	rndNum := rand.Float32() * 0xFFF
	id := uint64(nano<<32) + uint64(port<<16) + uint64((t&0xF)<<12) + uint64(rndNum)
	return id
}

func GetId() string {
	nano := time.Now().UnixNano()
	rand.Seed(nano)
	rndNum := rand.Int63()
	sessionId := Md5(Md5(strconv.FormatInt(nano, 10)) + Md5(strconv.FormatInt(rndNum, 10)))
	return sessionId
}

func Md5(text string) string {
	hashMd5 := md5.New()
	io.WriteString(hashMd5, text)
	return fmt.Sprintf("%x", hashMd5.Sum(nil))
}
